﻿using System;
using System.Net;

namespace ProxyFinder.Strategies {
    public class UserPromptCredentialStrategy : BaseCredentialStrategy {
        readonly IWindowsCredentialProvider _credentialProvider;

        public UserPromptCredentialStrategy(IWindowsCredentialProvider credentialProvider) {
            if(credentialProvider == null) {
                throw new ArgumentNullException("credentialProvider");
            }
            _credentialProvider = credentialProvider;
        }

        public override IWebProxy GetProxy(Uri uri) {
            WebProxy systemProxy = GetSystemProxy(uri);
            // If we did not succeed in getting a proxy by this time then let's try and prompt the user for
            // credentials and do that until we have succeeded. But we can only do this if the current ICredentialProvider
            // supports the correct IWindowsCredentialProvider interface
            WebProxy proxy = GetSystemProxy(uri);
            ICredentials basicCredentials = _credentialProvider.PromptForCredentials(systemProxy.Address.Host, true);
            // If the provider returned credentials that are null that means the user cancelled the prompt
            // and we want to stop at this point and return nothing.
            if(null == basicCredentials) {
                return null;
            }
            proxy.Credentials = basicCredentials;
            return proxy;
        }
    }
}